package org.example.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.Optional;

import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR;

/**
 * 请求日志过滤器组件
 * 实现GlobalFilter接口，用于在网关层记录请求路由信息
 */
@Component
public class RequestLoggingFilter implements GlobalFilter {

    // 创建日志记录器
    private static final Logger logger = LoggerFactory.getLogger(RequestLoggingFilter.class);

    /**
     * 过滤器核心方法
     * @param exchange 当前的服务器网络交换对象，包含请求和响应
     * @param chain 网关过滤器链，用于传递控制到下一个过滤器
     * @return Mono<Void> 表示异步处理完成
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取原始请求URL
        URI originalUri = exchange.getRequest().getURI();
        
        // 获取匹配的路由信息
        Route route = exchange.getAttribute(GATEWAY_ROUTE_ATTR);
        
        // 打印请求信息
        if (route != null) {
            // 如果有匹配的路由，记录请求URL、目标URI和路由ID
            logger.info("Incoming request: {} is routed to: {} with route ID: {}",
                        originalUri, route.getUri(), route.getId());
        } else {
            // 如果没有匹配的路由，记录请求URL
            logger.info("Incoming request: {} has no route matched", originalUri);
        }
        
        // 继续过滤器链的执行
        return chain.filter(exchange);
    }
}